import React, { Component } from 'react';
import PropTypes from "prop-types";
import { View, StyleSheet ,Dimensions,Platform} from 'react-native';
import Carousel, { Pagination } from '../../dependencies/react-native-snap-carousel/src/index';
import SliderEntry from './SliderEntry';
import Label from '../label/index';

import {getSliderStyle} from './SliderStyle'
import Variables from '../../config/theme/styles/index';


export default class Slider extends Component { 
    constructor(props) {
        super(props);
        
        this.state = {
            slider1ActiveSlide: this.props.firstItem,
        };
    }

    _renderItem({ item, index }) {   
        let { styles,SliderStyle} = getSliderStyle(Variables);   
        return (
            <SliderEntry
                data={item}
                itemWidth={this.props.itemWidth}
                itemHeight={this.props.itemHeight}
                itemRealWidth={this.props.itemRealWidth}
                clickFunc={this.props.clickFunc}
				activeOpacity={this.props.activeOpacity}
                index={index}
                defaultImg={this.props.defaultImg}
                imgMarginHorizontal={this.props.imgMarginHorizontal}
                imgMarginVertical={this.props.imgMarginVertical || SliderStyle.dotToImgVertical}
                itemAccessible={this.props.itemAccessible}
            />
        );
    }
   
    componentDidMount(){
        //解决不自定义onPress事件时，点击导致自动播放暂停问题
        if(this.props.autoPlay){
            this.autoplayInterval = setInterval(()=>{
                this.slider1Ref.startAutoplay();
            },this.props.duration);
        }   
    }
    stopAutoplay() {
        if (this.autoplayInterval) {
            clearInterval(this.autoplayInterval);
        }
        this.slider1Ref.stopAutoplay();
    }
    componentWillUnmount(){
        clearInterval(this.autoplayInterval);
    }

    _onSnapToItem(index){
        this.setState({ slider1ActiveSlide: index });
        if(this.props.snapToItem){
            this.props.snapToItem(index);
        }
    }

    _snapToItem(index){
        this.slider1Ref._snapToItem(this.slider1Ref._getPositionIndex(index));
    }

    render(){
        //获取slider的样式变量表 和 所需样式
        let { styles,SliderStyle} = getSliderStyle(Variables);
        let { slider1ActiveSlide} = this.state;
        let { data, pagination, sliderWidth, itemWidth, itemHeight, autoPlay,imgMaxSize,
            paginationBgColor,otherPaginationDotStyle,loop, duration, showCount, dotPosition,pagationLocation,pagationMargin,
            dotColor,dotActiveColor ,slideAlignment,firstItem,paginationDotStyle,paginationBottom,contentContainerStyle,loopClonesPerSide,isWidthCustom
        } = this.props;
        if (sliderWidth < itemWidth && !isWidthCustom) { 
            sliderWidth = itemWidth;
        }

        if(slideAlignment == 'center' || slideAlignment == 'start' || slideAlignment == 'end'){
            slideAlignment = slideAlignment;
        }else{
            slideAlignment = 'center';
        }

        let paginationStyle = [styles.paginationContainer];
        if(Platform.OS == 'harmony'){
            paginationStyle.push({
                zIndex:1
            })
        }
        if(dotPosition == 'outer'){
            paginationStyle.push({position:'relative'});
            paginationStyle.push({backgroundColor: paginationBgColor ? paginationBgColor:SliderStyle.paginationDotBgColor });
        }else{
            if(pagationLocation == 'left'){
                paginationStyle.push({justifyContent:'flex-start' ,marginLeft:pagationMargin ? pagationMargin :SliderStyle.pagationMarginVertical});
            }
            if(pagationLocation == 'right'){
                paginationStyle.push({justifyContent:'flex-end',marginRight:pagationMargin ? pagationMargin: SliderStyle.pagationMarginVertical});
              
            }
            paginationStyle.push({backgroundColor: paginationBgColor ? paginationBgColor:SliderStyle.innerDotBgColor });
        }

        paginationStyle.push({paddingBottom:paginationBottom ? paginationBottom :SliderStyle.dotPaddingBottom });
     
        let countArea;
        let countText = "共" + data.length + "张";
        if (showCount) { 
            countArea = (
                <View style={styles.count}>
                    <Label color='main' text={countText} type='description' />
                </View>
            );
        }
        //数据为图片时，控制最大显示数量
        if(data && data.length>0 && data[0].img){
            if(data.length>imgMaxSize){
                data = data.slice(0,imgMaxSize);
            }
        }
        return (     
            <View style={styles.marqueeContainer}>
                <Carousel
                    ref={(c) => this.slider1Ref = c}
                    data={data}
                    renderItem={this._renderItem.bind(this)}
                    sliderWidth={sliderWidth}
                    itemWidth={itemWidth}
                    itemHeight={itemHeight}
                    inactiveSlideScale={1}
                    inactiveSlideOpacity={1}
                    enableMomentum={false}
                    decelerationRate={'fast'}
                    activeSlideAlignment={slideAlignment}
                    autoplay={autoPlay}
                    autoplayDelay={1000}
                    autoplayInterval={duration}
                    loop={loop}
                    firstItem={firstItem}
                    removeClippedSubviews={false}
                    lockScrollWhileSnapping={true}
                    activeSlideOffset={0}
                    swipeThreshold={0}
                    onSnapToItem={(index) =>  this._onSnapToItem(index)}
                    contentContainerStyle={contentContainerStyle}
                    loopClonesPerSide={loopClonesPerSide}
                />
                {pagination ? 
                <Pagination
                    dotsLength={data.length}
                    activeDotIndex={slider1ActiveSlide}
                    containerStyle={paginationStyle}
                    dotContainerStyle={{marginHorizontal:0}}
                    dotStyle={[styles.paginationDot,paginationDotStyle]}
                    inactiveDotColor={dotColor ? dotColor : SliderStyle.noactiveDotColor}
                    dotColor={dotActiveColor ? dotActiveColor : SliderStyle.activeDotColor}
                    inactiveDotOpacity={1}
                    inactiveDotScale={1}
                    inactiveDotStyle={[styles.otherPaginationDot,otherPaginationDotStyle]}
                    carouselRef={this.slider1Ref}
                    tappableDots={!!this.slider1Ref}
                />
                 : <View></View>}
                {countArea}
          </View>

        );
    }

}

Slider.propTypes = {
     //数据，包括img,item,id
    data: PropTypes.any.isRequired,
    //Slider构件区域宽度
    sliderWidth: PropTypes.number,
    //每一项滑动项宽度
    itemWidth: PropTypes.number,
    //每一项滑动项高度
    itemHeight: PropTypes.number,
    //传入自定义构件真实宽度
    itemRealWidth: PropTypes.number,
    //是否自动播放
    autoPlay: PropTypes.bool,
    //自动播放间隔
    duration: PropTypes.number,
    //是否循环播放
    loop: PropTypes.bool,
    //是否显示下方总计
    showCount: PropTypes.bool,
    //图片加载失败默认图片
    defaultImg: PropTypes.any,
    //点击事件
    clickFunc: PropTypes.func,
	//组件按下时透明度
    activeOpacity: PropTypes.number,
    //自定义组件在slider滑动区域初始化位置
    slideAlignment: PropTypes.string,
    //首次展示数据的索引
    firstItem: PropTypes.number,
    //滑动到下一页时触发，参数为下一页的索引
    snapToItem: PropTypes.func,

    //是否显示页码指示器
    pagination: PropTypes.bool,
    //页码指示器背景颜色
    paginationBgColor: PropTypes.string,
    //页码指示器位置
    dotPosition: PropTypes.string,
    //页码指示器当前选中项颜色
    dotActiveColor: PropTypes.string,
    //页码指示器其余项颜色
    dotColor: PropTypes.string,
    //页码指示器当前选中项样式
    paginationDotStyle:PropTypes.object,
    //页码指示器其余项样式
    otherPaginationDotStyle:PropTypes.object,
    //页码指示器距离底部距离
    paginationBottom: PropTypes.number,

    //轮播数据为图片时图片距离容器上下间距、
    imgMarginVertical: PropTypes.number,
    //轮播数据为图片时图片距离容器左右间距
    imgMarginHorizontal: PropTypes.number,
    //轮播数据为图片时可显示的最大图片数量
    imgMaxSize: PropTypes.number,
    //容器样式
    contentContainerStyle:PropTypes.object,
    //页码指示器位置
    pagationLocation:PropTypes.string,
    //页码指示器边距
    pagationMargin:PropTypes.number,
    //循环时每一边克隆的数量
    loopClonesPerSide:PropTypes.number,
    //是否启用每一项的点击事件无障碍功能
    itemAccessible: PropTypes.bool,
    //slider为true时，传入自定义宽度
    isWidthCustom:PropTypes.bool
}

Slider.defaultProps = {
    sliderWidth: Dimensions.get('window').width,
    itemWidth: Dimensions.get('window').width,
    itemHeight: 200,
    autoPlay: true,
    duration: 4000,
    loop: true,
    pagination: true,
    showCount: false,
    activeOpacity: 1,
    dotPosition: 'inner',
    slideAlignment: 'center',
    firstItem: 0,
    paginationDotStyle:{},
    otherPaginationDotStyle:{},
    imgMarginHorizontal: 15,
    imgMaxSize: 10,
    contentContainerStyle:{},
    pagationLocation:'center',
    loopClonesPerSide:3,
    itemAccessible: true,
    isWidthCustom: false
}

